package org.jeecg.glr.iframe.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SysConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.glr.entity.GlrVideoBdRecognize;
import org.jeecg.glr.entity.GlrVideoYs;
import org.jeecg.glr.iframe.service.IGlrIframeVideoMonitoringService;
import org.jeecg.glr.iframe.util.AjaxJson;
import org.jeecg.glr.mapper.GlrVideoYsMapper;
import org.jeecg.glr.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.*;

import static org.jeecg.common.constant.CommonConstant.St_Access_Token;

@Service
public class GlrIframeVideoMonitoringService extends ServiceImpl<GlrVideoYsMapper, GlrVideoYs> implements IGlrIframeVideoMonitoringService {

    @Autowired
    @Lazy
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    @Lazy
    private RedisUtil redisUtil;

    @Autowired
    private GlrVideoYsMapper glrVideoYsMapper;

    @Value(value = "${glr.path.viewBmpPath}")
    private String viewBmpPath;


    public LoginUser updateUserInfo(HttpServletRequest request) throws Exception{
        String token=request.getParameter(St_Access_Token);
        if(StringUtil.isEmpty(token)){
            return null;
        }
        return checkUserTokenIsEffect(token);
    }

    public LoginUser getSessionUser() throws Exception{
        HttpSession session = SpringContextUtils.getHttpServletRequest().getSession();
        Object o1=session.getAttribute(St_Access_Token);
        LoginUser loginUser=checkUserTokenIsEffect(o1.toString());
        return loginUser;
    }

    public LoginUser checkUserTokenIsEffect(String token) throws AuthenticationException {
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(token);
        if (username == null) {
            return null;
        }

        // 查询用户信息
        log.warn("———校验token是否有效————checkUserTokenIsEffect——————— "+ token);
        LoginUser loginUser = sysBaseAPI.getUserByName(username);
        if (loginUser == null) {
            return null;
        }
        // 判断用户状态
        if (loginUser.getStatus() != 1) {
            return null;
        }
        // 校验token是否超时失效 & 或者账号密码是否错误
        if (!jwtTokenRefresh(token, username, loginUser.getPassword())) {
           return null;
        }

        return loginUser;
    }

    public boolean jwtTokenRefresh(String token, String userName, String passWord) {
        String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
        if (oConvertUtils.isNotEmpty(cacheToken)) {
            // 校验token有效性
            if (!JwtUtil.verify(cacheToken, userName, passWord)) {
                String newAuthorization = JwtUtil.sign(userName, passWord);
                // 设置超时时间
                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME *2 / 1000);
                log.warn("——————————用户在线操作，更新token保证不掉线—————————jwtTokenRefresh——————— "+ token);
            }
            //update-begin--Author:scott  Date:20191005  for：解决每次请求，都重写redis中 token缓存问题
//			else {
//				// 设置超时时间
//				redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
//				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
//			}
            //update-end--Author:scott  Date:20191005   for：解决每次请求，都重写redis中 token缓存问题
            return true;
        }
        return false;
    }

    public AjaxJson getFaceDetect(String fCount, String fId,LoginUser loginUser){
        //System.out.println("getFaceDetect");
        AjaxJson j = new AjaxJson();
        try{
            String stSql=
                    "select \n" +
                    "id,\n" +
                    "catalog,\n" +
                    "equipment_serial as equipmentSerial,\n" +
                    "take_photo_time_string as takePhotoTimeString,\n" +
                    "take_photo_time_date as takePhotoTimeDate,\n" +
                    "baidu_server_code as baiduServerCode,\n" +
                    "score,\n" +
                    "user_id as userId,\n" +
                    "user_info as userInfo,\n" +
                    "face_detect as face_detect\n" +
                    "from glr_video_bd_recognize where face_detect is not null ";

            if(loginUser!=null){
                if(!loginUser.getUserType().equals(SysConstant.SYS_USER_TYPE_0)&&!loginUser.getUserType().equals(SysConstant.SYS_USER_TYPE_ADMIN)){
                    stSql=stSql+" and sys_company_code='"+ loginUser.getSysCompanyCode()+"'";
                }
            }
            Long fid1=Long.parseLong(fId);
            if (fid1>0){
                stSql=stSql+" and id> " +fid1;
            }

            stSql=stSql+" order by id desc ";

            Long fcount1=Long.parseLong(fCount);
            if (fcount1>0){
                stSql=stSql+" limit " +fcount1;
            }

            List<Map<String, Object>> list1=glrVideoYsMapper.doGetListForJdbc(stSql);

            java.text.SimpleDateFormat s= new java.text.SimpleDateFormat("HH:mm:ss");

            List<GlrVideoBdRecognize> list=new ArrayList<>();
            for (Map<String, Object> entity0:list1){
                String stcatalog=entity0.get("catalog").toString();
                if (StringUtil.isEmpty(stcatalog)) stcatalog="";
                String stequipmentSerial=entity0.get("equipmentSerial").toString();
                if (StringUtil.isEmpty(stequipmentSerial)) stequipmentSerial="";
                String sttakePhotoTimeString=entity0.get("takePhotoTimeString").toString();
                if (StringUtil.isEmpty(sttakePhotoTimeString)) sttakePhotoTimeString="";
                GlrVideoBdRecognize entity1=new GlrVideoBdRecognize();
                String st1=viewBmpPath+stcatalog;
                entity1.setSysOrgCode(st1);
                String sttemp=sttakePhotoTimeString.substring(8,10)+":"+sttakePhotoTimeString.substring(10,12)+":"+sttakePhotoTimeString.substring(12,14);
                entity1.setSysCompanyCode(sttemp);
                entity1.setCatalog(stcatalog);
                entity1.setEquipmentSerial(stequipmentSerial);
                entity1.setTakePhotoTimeString(sttakePhotoTimeString);
                entity1.setId(sttakePhotoTimeString);
                entity1.setScore(Double.parseDouble(entity0.get("score").toString()));
                entity1.setFace_detect(entity0.get("face_detect").toString());
                entity1.setUserInfo(entity0.get("userInfo").toString());
                list.add(entity1);
            }

            Collections.sort(list, new Comparator<GlrVideoBdRecognize>() {
                @Override
                public int compare(GlrVideoBdRecognize u1, GlrVideoBdRecognize u2) {
                    long diff = u1.getTakePhotoTimeString().compareTo(u2.getTakePhotoTimeString());
                    if (diff > 0) {
                        return 1;
                    }else if (diff < 0) {
                        return -1;
                    }
                    return 0; //相等为0
                }
            }); // 排序

            j.setObj(list);
            j.setSuccess(true);

        }catch (Exception e){
            j.setSuccess(false);
            e.printStackTrace();
        }


        return j;
    }

}
